<template>
  <view class="search-page">
    <view class="search-bar">
      <uv-search v-model="keyword" placeholder="搜索商品" showAction actionText="搜索" @search="doSearch" @custom="doSearch" @change="onChange" />
    </view>

    <scroll-view class="body" scroll-y @scrolltolower="loadMore">
      <!-- 未搜索时显示历史与热门 -->
      <view v-if="!searched" class="section">
        <view class="section-title">历史搜索</view>
        <view v-if="history.length===0" class="empty-sub">暂无历史</view>
        <view class="tags">
          <uv-tags v-for="h in history" :key="h" :text="h" size="mini" plain @tap="tapHistory(h)" />
        </view>
        <view class="ops-right"><uv-button size="mini" plain @tap="clearHistory">清空</uv-button></view>
      </view>

      <view v-if="!searched" class="section">
        <view class="section-title">热门搜索</view>
        <view class="tags">
          <uv-tags v-for="hot in hots" :key="hot" :text="hot" type="warning" size="mini" plain @tap="tapHot(hot)" />
        </view>
      </view>

      <!-- 搜索结果列表 -->
      <view v-if="searched" class="section">
        <uv-empty v-if="!loading && list.length===0" mode="search" text="未找到相关商品" />
        <view class="goods" v-for="g in list" :key="g.id" @tap="goDetail(g)">
          <image class="cover" :src="g.cover" mode="aspectFill" />
          <view class="info">
            <view class="name">{{ g.name }}</view>
            <view class="price">¥ {{ g.price }}</view>
            <view class="sub">销量 {{ g.sales || 0 }}</view>
          </view>
          <uv-button size="mini" type="primary" shape="circle">购买</uv-button>
        </view>
        <view class="loadmore" v-if="!loading && hasMore">上拉加载更多</view>
      </view>

      <view class="pad" />
    </scroll-view>
  </view>
</template>

<script setup>
// 中文注释：全局搜索页（uv-ui）
import { ref, onMounted } from 'vue'
import { goodsApi } from '@/api/index.js'

const keyword = ref('')
const searched = ref(false)
const list = ref([])
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const loading = ref(false)
const history = ref([])
const hots = ref(['牛奶','水果','纸巾','米面粮油'])

const loadHistory = () => {
  try { history.value = uni.getStorageSync('search_history') || [] } catch (e) { history.value = [] }
}
const saveHistory = (k) => {
  if (!k) return
  const arr = [k, ...history.value.filter(x => x !== k)].slice(0, 10)
  history.value = arr
  uni.setStorageSync('search_history', arr)
}
const clearHistory = () => {
  history.value = []
  uni.removeStorageSync('search_history')
}

const onChange = (v) => { if (!v) searched.value = false }

const resetAndQuery = async () => {
  page.value = 1
  hasMore.value = true
  await query()
}

const query = async () => {
  if (loading.value || !hasMore.value) return
  loading.value = true
  try {
    const data = await goodsApi.searchGoods({ q: keyword.value, page: page.value, page_size: pageSize.value })
    const items = Array.isArray(data?.list) ? data.list : []
    list.value = page.value === 1 ? items : [...list.value, ...items]
    hasMore.value = items.length === pageSize.value
    page.value++
  } catch (e) {
    uni.showToast({ title: '搜索失败', icon: 'none' })
  } finally { loading.value = false }
}

const doSearch = async () => {
  if (!keyword.value) { uni.showToast({ title: '请输入关键词', icon: 'none' }); return }
  searched.value = true
  saveHistory(keyword.value)
  await resetAndQuery()
}
const loadMore = () => { if (searched.value) query() }
const tapHistory = (k) => { keyword.value = k; doSearch() }
const tapHot = (k) => { keyword.value = k; doSearch() }
const goDetail = (g) => { uni.navigateTo({ url: `/pages/goods/detail?id=${g.id}` }) }

onMounted(loadHistory)
</script>

<style scoped lang="scss">
.search-page { min-height: 100vh; background: $uni-bg-color-grey; }
.search-bar { background: #fff; padding: 12rpx 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.06); }
.body { height: calc(100vh - 100rpx); padding: 12rpx 16rpx; box-sizing: border-box; }
.section { background: #fff; border-radius: 16rpx; padding: 16rpx; margin-bottom: 16rpx; box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06); }
.section-title { font-size: 28rpx; color: #222; font-weight: 600; margin-bottom: 12rpx; }
.empty-sub { color: #999; font-size: 24rpx; }
.tags { display: flex; flex-wrap: wrap; gap: 12rpx; }
.ops-right { display: flex; justify-content: flex-end; margin-top: 12rpx; }

.goods { display: grid; grid-template-columns: 160rpx 1fr auto; gap: 12rpx; align-items: center; background: #fff; border-radius: 16rpx; padding: 12rpx; margin-bottom: 12rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.06); }
.cover { width: 160rpx; height: 160rpx; border-radius: 12rpx; background: #f2f2f2; }
.info { min-width: 0; }
.name { font-size: 28rpx; color: #222; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.price { color: $uni-color-primary; margin-top: 6rpx; font-weight: 700; }
.sub { color: #999; font-size: 22rpx; margin-top: 4rpx; }
.loadmore { text-align: center; color: #999; padding: 20rpx 0; }
.pad { height: 40rpx; }
</style>
